<template>
  <div class="doc-list-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 v-if="currentCategory">{{ currentCategory.name }}</h1>
      <h1 v-else>全部文档</h1>
      
      <p v-if="currentCategory?.description" class="category-desc">
        {{ currentCategory.description }}
      </p>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-form :inline="true">
        <el-form-item label="难度">
          <el-select v-model="filters.difficulty" clearable placeholder="全部">
            <el-option label="入门" value="beginner" />
            <el-option label="进阶" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序">
          <el-select v-model="filters.sortBy">
            <el-option label="最新更新" value="updated" />
            <el-option label="最多浏览" value="views" />
            <el-option label="标题排序" value="title" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-input
            v-model="filters.keyword"
            placeholder="搜索文档..."
            clearable
            @clear="handleFilter"
            @keyup.enter="handleFilter"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 文档列表 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="filteredDocs.length" class="doc-grid">
      <div
        v-for="doc in paginatedDocs"
        :key="doc.id"
        class="doc-card"
        @click="goToDoc(doc)"
      >
        <!-- 文档标题 -->
        <h3 class="doc-title">{{ doc.title }}</h3>
        
        <!-- 文档摘要 -->
        <p class="doc-excerpt">
          {{ doc.excerpt || truncateContent(doc.content) }}
        </p>
        
        <!-- 文档元信息 -->
        <div class="doc-meta">
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            {{ formatDate(doc.updatedAt) }}
          </span>
          <span class="meta-item">
            <el-icon><View /></el-icon>
            {{ doc.viewCount }} 次浏览
          </span>
          <el-tag 
            v-if="doc.difficulty" 
            :type="getDifficultyType(doc.difficulty)"
            size="small"
          >
            {{ getDifficultyText(doc.difficulty) }}
          </el-tag>
        </div>
        
        <!-- 文档标签 -->
        <div v-if="doc.tags?.length" class="doc-tags">
          <el-tag
            v-for="tag in doc.tags.slice(0, 3)"
            :key="tag.id"
            size="small"
            type="info"
          >
            {{ tag.name }}
          </el-tag>
          <span v-if="doc.tags.length > 3" class="more-tags">
            +{{ doc.tags.length - 3 }}
          </span>
        </div>
      </div>
    </div>
    
    <el-empty v-else description="暂无文档" />
    
    <!-- 分页 -->
    <div v-if="filteredDocs.length > pageSize" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="filteredDocs.length"
        layout="prev, pager, next, total"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search, Clock, View } from '@element-plus/icons-vue'
import { useDocsStore } from '@/stores/docs'
import type { DocLesson } from '@/types/docs'

const route = useRoute()
const router = useRouter()
const docsStore = useDocsStore()

// 状态
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)

// 筛选条件
const filters = ref({
  difficulty: '',
  sortBy: 'updated',
  keyword: ''
})

// 获取当前分类
const currentCategory = computed(() => {
  const categorySlug = route.params.category as string
  if (!categorySlug) return null
  
  return docsStore.categories.find(cat => cat.slug === categorySlug)
})

// 获取文档列表
const docs = computed(() => {
  if (currentCategory.value) {
    return docsStore.lessonsByCategory.get(currentCategory.value.id) || []
  }
  return docsStore.lessons
})

// 过滤后的文档
const filteredDocs = computed(() => {
  let result = [...docs.value]
  
  // 难度筛选
  if (filters.value.difficulty) {
    result = result.filter(doc => doc.difficulty === filters.value.difficulty)
  }
  
  // 关键词搜索
  if (filters.value.keyword) {
    const keyword = filters.value.keyword.toLowerCase()
    result = result.filter(doc => 
      doc.title.toLowerCase().includes(keyword) ||
      doc.excerpt?.toLowerCase().includes(keyword) ||
      doc.content.toLowerCase().includes(keyword)
    )
  }
  
  // 排序
  switch (filters.value.sortBy) {
    case 'updated':
      result.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
      break
    case 'views':
      result.sort((a, b) => b.viewCount - a.viewCount)
      break
    case 'title':
      result.sort((a, b) => a.title.localeCompare(b.title))
      break
  }
  
  return result
})

// 分页后的文档
const paginatedDocs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDocs.value.slice(start, end)
})

// 方法
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

const truncateContent = (content: string, maxLength = 150) => {
  if (content.length <= maxLength) return content
  return content.substring(0, maxLength) + '...'
}

const getDifficultyType = (difficulty: string) => {
  const map: Record<string, string> = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return map[difficulty] || ''
}

const getDifficultyText = (difficulty: string) => {
  const map: Record<string, string> = {
    beginner: '入门',
    intermediate: '进阶',
    advanced: '高级'
  }
  return map[difficulty] || ''
}

const goToDoc = (doc: DocLesson) => {
  router.push(`/docs/lesson/${doc.slug || doc.id}`)
}

const handleFilter = () => {
  currentPage.value = 1
}

const loadData = async () => {
  loading.value = true
  try {
    await docsStore.fetchDocLessons({
      categoryId: currentCategory.value?.id
    })
  } finally {
    loading.value = false
  }
}

// 监听路由变化
watch(() => route.params.category, () => {
  loadData()
})

// 监听筛选条件变化
watch(filters, () => {
  currentPage.value = 1
}, { deep: true })

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.doc-list-page {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 2rem;
  
  h1 {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
  }
  
  .category-desc {
    color: var(--el-text-color-secondary);
    font-size: 1.125rem;
  }
}

.filter-bar {
  background-color: var(--el-bg-color);
  border-radius: 0.5rem;
  padding: 1rem;
  margin-bottom: 2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.loading-container {
  padding: 2rem;
}

.doc-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
  margin-bottom: 3rem;
}

.doc-card {
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 0.5rem;
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.doc-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.75rem;
  color: var(--el-text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.doc-excerpt {
  color: var(--el-text-color-regular);
  font-size: 0.875rem;
  line-height: 1.5;
  margin-bottom: 1rem;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.doc-meta {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 0.75rem;
  font-size: 0.75rem;
  color: var(--el-text-color-secondary);
  
  .meta-item {
    display: flex;
    align-items: center;
    gap: 0.25rem;
  }
}

.doc-tags {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  
  .el-tag {
    cursor: inherit;
  }
  
  .more-tags {
    font-size: 0.75rem;
    color: var(--el-text-color-secondary);
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 3rem;
}

@media (max-width: 768px) {
  .doc-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .filter-bar {
    .el-form {
      display: block;
      
      .el-form-item {
        display: block;
        margin-bottom: 1rem;
      }
    }
  }
}
</style> 